package com.wechatapp.mengyao.poetry.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wechatapp.mengyao.poetry.core.CurrentContext;
import com.wechatapp.mengyao.poetry.core.PageResult;
import com.wechatapp.mengyao.poetry.dto.ClearPlaybackHistoryDTO;
import com.wechatapp.mengyao.poetry.dto.UpdatePlayBackHistoryDTO;
import com.wechatapp.mengyao.poetry.entity.Media;
import com.wechatapp.mengyao.poetry.entity.PlaybackHistory;
import com.wechatapp.mengyao.poetry.mapper.MediaMapper;
import com.wechatapp.mengyao.poetry.mapper.PlaybackHistoryMapper;
import com.wechatapp.mengyao.poetry.service.PlaybackHistoryService;
import com.wechatapp.mengyao.poetry.vo.PlaybackHistoryView;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @author yanghuaxu
 * @date 2025/7/11 16:13
 */
@Service
@Slf4j
public class PlaybackHistoryServiceImpl implements PlaybackHistoryService {

    @Autowired
    private PlaybackHistoryMapper playbackHistoryMapper;
    @Autowired
    private MediaMapper mediaMapper;

    @Override
    public PageResult<PlaybackHistoryView> getCurrentUserPlaybackHistory(Map<String, String> map) {
        map.putIfAbsent("userId", String.valueOf(CurrentContext.getCurrentOperatingUser().getUserId()));
        return getPlaybackHistoryByUserId(map);
    }

    @Override
    public PageResult<PlaybackHistoryView> getPlaybackHistoryByUserId(Map<String, String> map) {
        int pageNum = Integer.parseInt(map.getOrDefault("pageNum", "1"));
        int pageSize = Integer.parseInt(map.getOrDefault("pageSize", "10"));
        Assert.isTrue(map.containsKey("userId"), "缺少必填参数userId");
        PageHelper.startPage(pageNum, pageSize, true);
        List<PlaybackHistoryView> playbackHistoryList = playbackHistoryMapper.getPlaybackHistoryByUserId(Long.parseLong(map.get("userId")));
        return PageResult.fromPage((Page<PlaybackHistoryView>) playbackHistoryList, playbackHistoryList);
    }

    @Override
    public void updateUserPlaybackHistory(UpdatePlayBackHistoryDTO updatePlayBackHistory) {
        PlaybackHistory mediaPlayHistory = getMediaPlayHistory(updatePlayBackHistory.getUserId(), updatePlayBackHistory.getMediaId());
        Media media = mediaMapper.selectByPrimaryKey(updatePlayBackHistory.getMediaId());
        Long progressSeconds = updatePlayBackHistory.getProgressSeconds();
        if (progressSeconds > media.getDuration()) {
            progressSeconds = media.getDuration();
        }
        if (ObjectUtils.isEmpty(mediaPlayHistory)) {
            PlaybackHistory history = new PlaybackHistory();
            history.setMediaId(updatePlayBackHistory.getMediaId());
            history.setUserId(updatePlayBackHistory.getUserId());
            history.setStartTime(LocalDateTime.now());
            history.setProgressSeconds(progressSeconds);
            history.setDurationSeconds(media.getDuration());
            history.setMediaType(media.getMediaType());
            history.setIsFinished(media.getDuration() <= updatePlayBackHistory.getProgressSeconds());
            playbackHistoryMapper.insertSelective(history);
            log.info("不存在播放记录，新增记录");
        } else {
            mediaPlayHistory.setProgressSeconds(progressSeconds);
            mediaPlayHistory.setIsFinished(media.getDuration() <= updatePlayBackHistory.getProgressSeconds());
            playbackHistoryMapper.updateByPrimaryKeySelective(mediaPlayHistory);
            log.info("存在播放记录，更新记录");
        }
    }

    @Override
    public PlaybackHistory getMediaPlayHistory(Long userId, Long mediaId) {
        PlaybackHistory condition = new PlaybackHistory();
        condition.setMediaId(mediaId);
        condition.setUserId(userId);
        return playbackHistoryMapper.selectOne(condition);
    }

    @Override
    public int clearPlaybackHistory(ClearPlaybackHistoryDTO clearPlaybackHistory) {
        int result;
        Assert.notNull(clearPlaybackHistory.getUserId(), "userId不能为空");
        if (clearPlaybackHistory.getClearAll()) {
            PlaybackHistory condition = new PlaybackHistory();
            condition.setUserId(clearPlaybackHistory.getUserId());
            result = playbackHistoryMapper.delete(condition);
        } else {
            Example example = new Example(PlaybackHistory.class);
            example.createCriteria().andIn("mediaId", clearPlaybackHistory.getMediaIdList())
                    .andEqualTo("userId", clearPlaybackHistory.getUserId());
            result = playbackHistoryMapper.deleteByExample(example);
        }
        return result;
    }
}
